#include "ustylebutton.h"
#include "uwidgetutils.h"

#include <QPainterPath>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>

UStyleButton::UStyleButton(const QString text, QWidget* parent) : QPushButton(text, parent)
{
}

UStyleButton::UStyleButton(QWidget* parent) : QPushButton(parent)
{
}

void UStyleButton::setRadius(int radius)
{
    if (m_radius != radius)
    {
        m_radius = radius;
        update();
    }
}

void UStyleButton::setHoverColor(QColor color)
{
    m_color = color;
}

void UStyleButton::setRadiuPosition(RadiuPosition position)
{
    if (m_position != position)
    {
        m_position = position;
        update();
    }
}

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
void UStyleButton::enterEvent(QEvent* e)
#else
void UStyleButton::enterEvent(QEnterEvent* e)
#endif
{
    m_isEnter = true;
    QPushButton::enterEvent(e);
}

void UStyleButton::leaveEvent(QEvent* e)
{
    m_isEnter = false;
    QPushButton::leaveEvent(e);
}

void UStyleButton::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event)

    int padding = 2;
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    QRect rect = this->rect();
    QPalette pa = this->palette();

    QPainterPath framePath = UWidgetUtils::roundedPath(m_radius, rect, m_position);
    painter.setClipPath(framePath);

    if (m_isEnter)
    {
        painter.setBrush(m_color.isValid() ? m_color : QBrush(pa.color(QPalette::Button)));
        painter.setPen(Qt::NoPen);
        painter.drawPath(framePath);
    }

    if (isDown())
    {
        QColor color = pa.color(QPalette::Button);
        color = color.darker(120);
        painter.fillPath(framePath, color);
    }

    QStyleOptionButton btn;
    initStyleOption(&btn);
    QStylePainter stylePainter(this);
    stylePainter.drawControl(QStyle::CE_PushButtonLabel, btn);

    if (!isFlat())
    {
        painter.save();
        painter.setBrush(Qt::NoBrush);
        painter.setPen(QPen(isDown() ? pa.color(QPalette::Highlight) : pa.color(QPalette::WindowText), padding));
        painter.drawPath(framePath);
        painter.restore();
    }
}
